package com.blockmeta.bbs.businesslibrary.websocket;

import android.os.Handler;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.businesslibrary.pojo.websocket.AlivePOJO;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class HeartBeat
{
	protected Handler 		m_hdSend, m_hdRecv;
	protected IHBListener 	m_listener;
	protected int			m_nInterval = 10000;
    protected ConnectManager m_connManager;
	
	public HeartBeat(ConnectManager mgr)
	{
		m_hdSend = new Handler();
		m_hdRecv = new Handler();
        m_connManager = mgr;
		if(!ConnectCenter.getConnectCenter().isRegistered(this)) {
			ConnectCenter.getConnectCenter().register(this);
		}
	}
	
	public void setHBListener(IHBListener ihbListener)
	{
		m_listener = ihbListener;
	}
		
	protected void sendAlive()
	{
		AlivePOJO packet = new AlivePOJO();
		packet.set_pt("heartbeat");
        m_connManager.write(packet);
//		LogUtils.d("market heartbeat");
	}
	
	protected Runnable m_runSend = new Runnable() 
	{
		@Override
		public void run()
		{
			sendAlive();
			m_hdSend.postDelayed(this, m_nInterval);
		}
	};
		
	protected Runnable m_runRecv = new Runnable() 
	{
		@Override
		public void run() 
		{
			if (m_listener != null)
			{
				m_listener.onDisConnect();
			}
		}
	};	
	
	protected void checkAliveStatus()
	{		
		if (m_runRecv != null)
		{
			m_hdRecv.removeCallbacks(m_runRecv);
		}
	
		m_hdRecv.postDelayed(m_runRecv, m_nInterval * 3);
	}
	
	public void processAliveStatus()
	{		
		if (m_listener != null)
		{
			m_listener.onAliveStatus();
		}
		
		if (m_runRecv != null)
		{
			m_hdRecv.removeCallbacks(m_runRecv);
			checkAliveStatus();
		}
	}

	protected void startHB()
	{
		if (m_nInterval == 0)
		{
			m_nInterval = 90000;
		}

		m_hdSend.postDelayed(m_runSend, m_nInterval);
		checkAliveStatus();
	}

//	public void onEventMainThread(Event_LoginConnectOK ev)
//	{
//		if (m_connManager.getServerType() == ConnectManager.ServerType.Login)
//		{
//			startHB();
//		}
//	}
//
//	public void onEvent(Event_LoginConnectClose ev)
//	{
//		if (m_connManager.getServerType() == ConnectManager.ServerType.Login)
//		{
//			if (m_hdSend != null && m_runSend != null)
//			{
//				m_hdSend.removeCallbacks(m_runSend);
//			}
//		}
//	}
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEventMainThread(ConnectManager.Event_ConnectOK ev)
	{
		startHB();
	}
	@Subscribe
	public void onEvent(ConnectManager.Event_ConnectClose ev)
	{
		if (m_hdSend != null && m_runSend != null)
		{
			m_hdSend.removeCallbacks(m_runSend);
		}
	}

	public interface IHBListener
	{
		void onDisConnect();		
		void onAliveStatus();
	}
}
